//
//  CreateWalkmanWordListViewController.swift
//  ShimaPlayer
//
//  Created by michael on 2025/7/9.
//

import UIKit

class CreateWalkmanWordListViewController: UIViewController {
    
    private lazy var backButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "nav_back_gray")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "创建随身听词单"
        label.textColor = UIColor(hexString: "FFFFFF")
        label.font = .systemFont(ofSize: 17, weight: .medium)
        label.textAlignment = .center
        return label
    }()
    
    private lazy var coverView: ListCoverView = {
        let view = ListCoverView()
        view.onClick = { [weak self] in
            self?.showCoverPicker()
        }
        return view
    }()

    private var wordListNameLabel: UILabel = {
        let label = UILabel()
        label.text = "250307T1新编日语第2册词单"
        label.textColor = UIColor(hexString: "FFFFFF")
        label.font = .systemFont(ofSize: 13)
        return label
    }()

    private lazy var wordListView: WordListView = {
        let view = WordListView(title: "已添加的单词") { [weak self] in
            self?.onTapAddWord()
        }
        return view
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.isHidden = true
        setupUI()
    }
    
    func setupUI() {
        let bgImage = UIImage.gradientImage(colors: [UIColor(hexString: "#1B2340"), UIColor(hexString: "#1C2341"), UIColor(hexString: "#363F65")],
                                            size: view.bounds.size,
                                            startPoint: CGPoint(x: 0.25, y: 0.5),
                                            endPoint: CGPoint(x: 0.75, y: 0.5),
                                            locations: [0, 0.15, 0.46],
                                            transform: CATransform3DMakeAffineTransform(CGAffineTransform(a: 1.2, b: 1.24, c: -1.24, d: 0.25, tx: 0.51, ty: -0.36))
        )
        let bgView = UIImageView(image: bgImage)
        view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        view.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(10)
            make.leading.equalToSuperview().offset(16)
            make.height.equalTo(44)
            make.width.equalTo(20)
        }

        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerY.equalTo(backButton)
            make.centerX.equalToSuperview()
        }

        view.addSubview(coverView)
        coverView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(28)
            make.centerX.equalToSuperview()
            make.width.height.equalTo(100)
        }

        let editIcon = UIImageView(image: UIImage(named: "btn_icon_edit"))
        editIcon.contentMode = .scaleAspectFit
        let wordListNameView = TipsView(elements: [wordListNameLabel, editIcon]) { [weak self] in
            self?.onTapEditWordListName()
        }
        wordListNameView.layer.cornerRadius = 17.5
        view.addSubview(wordListNameView)
        wordListNameView.snp.makeConstraints { make in
            make.top.equalTo(coverView.snp.bottom).offset(24)
            make.centerX.equalToSuperview()
            make.height.equalTo(35)
        }

        view.addSubview(wordListView)

        let bottomBar = UIView()
        bottomBar.backgroundColor = UIColor(hexString: "#FFFFFF")
        view.addSubview(bottomBar)
        bottomBar.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(Size.bottomSafeAreaHeight + 50)
        }
        wordListView.snp.makeConstraints { make in
            make.top.equalTo(wordListNameView.snp.bottom).offset(22)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(bottomBar.snp.top)
        }
        
        let divider = UIView()
        divider.backgroundColor = UIColor(hexString: "#F5F5F5")
        bottomBar.addSubview(divider)
        divider.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(1)
        }

        let createButton = UIButton(type: .system)
        createButton.setTitle("创建此词单", for: .normal)
        createButton.setTitleColor(.white, for: .normal)
        createButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .bold)
        createButton.setTitleColor(UIColor(hexString: "#FFFFFF"), for: .highlighted)
        createButton.addTarget(self, action: #selector(onTapCreateWordList), for: .touchUpInside)
        createButton.backgroundColor = UIColor(hexString: "#5E62AC")
        createButton.layer.cornerRadius = 19
        bottomBar.addSubview(createButton)
        createButton.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(6)
            make.horizontalEdges.equalToSuperview().inset(16)
            make.height.equalTo(38)
        }
    }
    
    // MARK: - Actions
    @objc private func backButtonTapped() {
        navigationController?.popViewController(animated: true)
    }

    @objc private func onTapCreateWordList() {
        let list = [WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                    WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                    WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ")]
        wordListView.dataSource = list
    }

    private func showCoverPicker() {
//        let picker = UIImagePickerController()
//        picker.delegate = self
//        picker.sourceType = .photoLibrary
//        present(picker, animated: true, completion: nil)
    }
    
    private func onTapEditWordListName() {
        
    }

    private func onTapAddWord() {
        
    }

}

class ListCoverView: UIView {
    var coverUrl: String?
    var onClick: (() -> Void)?

    private let coverImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor(hexString: "FFFFFF")
        layer.cornerRadius = 10

        addSubview(coverImageView)
        coverImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        let tipLabel = UILabel()
        tipLabel.text = "编辑封面"
        tipLabel.textColor = UIColor(hexString: "FFFFFF")
        tipLabel.font = .systemFont(ofSize: 13)
        
        let tipView = TipsView(elements: [tipLabel])
        tipView.layer.cornerRadius = 10
        addSubview(tipView)

        tipView.snp.makeConstraints { make in
            make.bottom.equalToSuperview().inset(10)
            make.centerX.equalToSuperview()
            make.height.equalTo(20)
        }

        let tap = UITapGestureRecognizer(target: self, action: #selector(tapTipView))
        addGestureRecognizer(tap)
    }

    @objc private func tapTipView() {
        onClick?()
    }
}

class TipsView: UIView {
    
    var onClick: (() -> Void)?
    var elements: [UIView] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    convenience init(elements: [UIView], onClick: (() -> Void)? = nil) {
        self.init(frame: .zero)
        self.elements = elements
        self.onClick = onClick
        setupUI()
    }
    
    private func setupUI() {
        backgroundColor = .black.withAlphaComponent(0.4)

        let stackView = UIStackView(arrangedSubviews: elements)
        stackView.axis = .horizontal
        stackView.spacing = 17
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.horizontalEdges.equalToSuperview().inset(12)
        }

        let tap = UITapGestureRecognizer(target: self, action: #selector(tapTipView))
        addGestureRecognizer(tap)
    }

    @objc private func tapTipView() {
        onClick?()
    }
    
    func hiddenBg() -> Self {
        backgroundColor = .clear
        return self
    }
}

class WordListView: UIView, UITableViewDataSource, UITableViewDelegate {

    private var title: String?
    private var onTapAddButtonAction: (() -> Void)?
    var dataSource: [WordItemModel] = [] {
        didSet {
            tableView.reloadData()
        }
    }

    private let tableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = UIColor(hexString: "FFFFFF")
        tableView.rowHeight = 85
        return tableView
    }()
        
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    convenience init(title: String? = nil, onTapAddButton: (() -> Void)?) {
        self.init(frame: .zero)
        self.title = title
        self.onTapAddButtonAction = onTapAddButton
        setupUI()
    }

    private func setupUI() {
        tableView.dataSource = self
        tableView.delegate = self
        
        let top = UIView()
        top.backgroundColor = UIColor(hexString: "FFFFFF")
        top.layer.cornerRadius = 10

        let titleLabel = UILabel()
        titleLabel.text = title
        titleLabel.textColor = UIColor(hexString: "#5E62AC")
        titleLabel.font = .systemFont(ofSize: 16, weight: .bold)
        
        top.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.centerX.equalToSuperview()
        }
        
        let addButton = UIButton(type: .system)
        addButton.setImage(UIImage(named: "btn_add_word")?.withRenderingMode(.alwaysOriginal), for: .normal)
        addButton.addTarget(self, action: #selector(onTapAddButton), for: .touchUpInside)
        top.addSubview(addButton)
        addButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().inset(6)
            make.centerY.equalTo(titleLabel)
            make.width.height.equalTo(38)
        }
        
        addSubview(top)
        
        addSubview(tableView)
        
        top.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(65)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(55)
            make.leading.bottom.trailing.equalToSuperview()
        }
    }

    @objc private func onTapAddButton() {
        onTapAddButtonAction?()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        dataSource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WordItemCell = WordItemCell.cell(withTableView: tableView)
        cell.selectionStyle = .none
        let item = dataSource[indexPath.row]
        cell.configure(with: item)
        return cell
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            dataSource.remove(at: indexPath.row)
        }
    }
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    
//    func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
//        if let cell = tableView.cellForRow(at: indexPath) {
//            cell.contentView.layer.cornerRadius = 10
//            cell.contentView.clipsToBounds = true
//        }
//    }
//
//    func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
//        if let indexPath, let cell = tableView.cellForRow(at: indexPath) {
//            cell.contentView.layer.cornerRadius = 0
//            cell.contentView.clipsToBounds = false
//        }
//    }
}

class WordItemCell: UITableViewCell {
    private let originalLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16, weight: .medium)
        label.textColor = UIColor(hexString: "#1C1F1E")
        return label
    }()
    
    private let translationLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 13)
        label.textColor = UIColor(hexString: "#868F99")
        return label
    }()
    
    private let typeLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 9)
        label.textColor = UIColor(hexString: "#15CC9D")
        label.backgroundColor = UIColor(hexString: "#15CC9D")?.withAlphaComponent(0.1)
        label.layer.cornerRadius = 6.5
        return label
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

//    override func layoutSubviews() {
//        super.layoutSubviews()
//        /// 查找承载侧滑的父视图
//        if let superView = self.superview, NSStringFromClass(superView.classForCoder) == "_UITableViewCellSwipeContainerView" {
//            /// 修改Cell圆角样式
//            let maskPath = UIBezierPath(roundedRect: superView.bounds, cornerRadius: 16)
//            let maskLayer = CAShapeLayer()
//            maskLayer.frame = superView.bounds
//            maskLayer.path = maskPath.cgPath
//            superView.layer.mask = maskLayer
//            /// 查找侧滑删除摁钮视图
//            if let subView = superView.subviews.first, NSStringFromClass(subView.classForCoder) == "UISwipeActionPullView" {
//                /// 修改侧滑视图背景色和摁钮背景色
////                subView.backgroundColor = UIColor.design(.design_FF5050)
////                let btn = subView.subviews.last
////                btn?.backgroundColor = UIColor.design(.design_FF5050)
//            }
//        }
//    }
    
    func setupUI() {
        backgroundColor = .red
        contentView.backgroundColor = .white
        
        addSubview(originalLabel)
        originalLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(20)
            make.leading.equalToSuperview().offset(16)
        }
        
        let stack = UIStackView(arrangedSubviews: [typeLabel, translationLabel])
        stack.axis = .horizontal
        stack.spacing = 4
        
        addSubview(stack)
        stack.snp.makeConstraints { make in
            make.top.equalTo(originalLabel.snp.bottom).offset(10)
            make.leading.equalToSuperview().offset(16)
        }
        
        typeLabel.snp.makeConstraints { make in
            make.height.equalTo(13)
        }
    }
    
    func configure(with model: WordItemModel) {
        originalLabel.text = model.original
        translationLabel.text = model.translation
        typeLabel.text = model.type
    }
}

struct WordItemModel: Hashable {
    let original: String
    let translation: String
    let type: String
}
